<?php
/**
 * Created by PhpStorm.
 * User: yangt
 * Date: 2019/8/27
 * Time: 11:49
 */

namespace app\mall\controller\api;

use think\Controller;

class Bookmark extends Controller {
    protected $Model;

    public function initialize()
    {
        parent::initialize();
        config('default_return_type', 'json');
        $this->Model = model('MallBookmark');
    }

    /*
     * 收藏列表
     */
    public function index()
    {
        $bookmark_list = [];
        if( ! \yunbao\user::is_login()) {
            $this->error('请先登录！');
        }

        $bookmark_list = $this->Model->field('')->where(['user_id'=>\yunbao\user::is_login(),'status'=> 0])->select();

        if($bookmark_list){
            return ['code' => 200, 'data' => $bookmark_list, 'message' => '获取收藏列表成功！'];
        } else {
            return ['code' => 404, 'data' => $bookmark_list, 'message' => '获取收藏列表失败！'];
        }
    }

    /*
     * 新增收藏
     */
    public function add()
    {
        $id  = input('id', '0', 'intval');

        if( ! \yunbao\user::is_login()) {
            $this->error('请先登录！');
        }

        $goods = model('mall/mallGoods')->where(['id'=>$id])->find();

        if($goods){
            $data['user_id'] = \yunbao\user::is_login();
            $data['category_id'] = $goods['category_id'];
            $data['goods_id']     = $goods['id'];
            $data['status']     =1;

            if(model('mall/MallBookmark')->save($data)){
                $this->success('商品收藏成功！',url('mall/my.bookmark/index'));
            } else {
                return ['code' => 404, 'data' => $id, 'message' => '商品收藏失败！'];
            }

        } else {
            return ['code' => 404, 'data' => $id, 'message' => '请选择需要收藏的商品'];
        }
    }

    /*
     * 取消收藏
     */
    public function del()
    {
        $id  = input('id', '0', 'intval');

        if( ! \yunbao\user::is_login()) {
            $this->error('请先登录！');
        }

        if(!empty($id))
        {
//            model('mall/MallOrder')->destroy(['goods_id' => $id ])
            if($this->Model->where(['user_id'=>\yunbao\user::is_login(),'id'=>$id])->setField('status', '-1')){
                return $this->success('商品已取消收藏！',url('mall/my.bookmark/index'));
            } else {
                return ['code' => 404, 'data' => $id, 'message' => '商品取消收藏失败！'];
            }
        }else{
            return ['code' => 404, 'data' => $id, 'message' => '请选择需要取消收藏的商品'];
        }
    }
}